package com.takeshequ.nearest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.takeshequ.PullAndLoadListView;
import com.takeshequ.PullAndLoadListView.OnLoadMoreListener;
import com.takeshequ.PullToRefreshListView.OnRefreshListener;
import com.takeshequ.Constants;
import com.takeshequ.R;
import com.takeshequ.SMApplication;
import com.takeshequ.chat.ExpressionUtil;
import com.takeshequ.friends.BaseData;
import com.takeshequ.homepage.HomePageActivity;
import com.takeshequ.main.BasicFragment;
import com.utils.HttpClientUtils;
import com.utils.HttpClientUtils.HttpResponseHandler;
import com.utils.SharedPreferencesUtils;

public class NearestFragment extends BasicFragment implements
		AdapterView.OnItemClickListener {
	private static final String TAG = "NearestFragment";
	static Context context = null;
	private static Gson gson;
	private static SMApplication application;
	private static int pageNumber = 1;
	private View processView, nearestView;
	private Map<Integer, View> viewMap = new HashMap<Integer, View>();

	public static NearestFragment newInstance(Context con, SMApplication app) {
		context = con;
		application = app;
		gson = new Gson();
		NearestFragment newFragment = new NearestFragment();
		return newFragment;

	}

	private static ArrayList<NearestListItem> items;
	static {
		items = new ArrayList<NearestListItem>();
	}

	private PullAndLoadListView listView;
	private ItemAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void getListItems(final AsyncHttpResponseHandler handler) {
		items.clear();
		Map<String, String> params = new HashMap<String, String>();
		params.put("scope", "2000000");
		params.put("sex", SharedPreferencesUtils.getInstance(context)
				.getNearestListGender());
		params.put("pageNumber", String.valueOf(pageNumber));
		HttpClientUtils.get("listNearbyMember", params,
				new HttpResponseHandler() {

					@Override
					public void handler(String response) {
						handler.onSuccess(response);
					}
				});
	}

	@Override
	public void onResume() {
		super.onResume();
		getListItems(new RefreshAsyncHttpResponseHandler());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.nearest_list, container, false);
		nearestView = view.findViewById(R.id.nearest_listview_layout);
		processView = view.findViewById(R.id.nearest_list_view_process);
		listView = (com.takeshequ.PullAndLoadListView) view
				.findViewById(R.id.nearest_listview);
		listView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				listView.postDelayed(new Runnable() {
					@Override
					public void run() {
						resetPageNumber();
						getListItems((new RefreshAsyncHttpResponseHandler()));
						listView.onRefreshComplete();
					}
				}, 2000);
			}
		});
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				pageNumberAddOne();
				// getListItems();
				listView.onRefreshComplete();
			}
		});

		adapter = new ItemAdapter(inflater);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				NearestListItem item = items.get(arg2);
				// Constants.firend = BaseData.getFriend(item.getMemberId());
				Constants.selectMemberId = item.getMemberId();
				Intent intent = new Intent(context, HomePageActivity.class);
				startActivity(intent);
			}
		});
		return view;
	}

	class RefreshAsyncHttpResponseHandler extends AsyncHttpResponseHandler {

		@Override
		public void onStart() {
			super.onStart();
			processView.setVisibility(View.VISIBLE);
		}

		@Override
		public void onSuccess(String response) {
			try {
				JSONObject jsonObject = new JSONObject(response);
				items = gson.fromJson(jsonObject.getString("memberList"),
						new TypeToken<List<NearestListItem>>() {
						}.getType());
				listView.onRefreshComplete();
				adapter.notifyDataSetChanged();
				processView.setVisibility(View.GONE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void resetPageNumber() {
		pageNumber = 1;
	}

	private void pageNumberAddOne() {
		pageNumber = pageNumber + 1;
	}

	private void pageNumberReduceOne() {
		if (pageNumber > 1) {
			pageNumber = pageNumber - 1;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		// Toast.makeText(context, adapter.getItem(i).getNickName(),
		// Toast.LENGTH_SHORT).show();
	}

	class ItemAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private class ViewHolder {
			public TextView nickName, signature, distance, age, constellation;
			public ImageView headImage, genderImage;
		}

		public ItemAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (items.size() > position) {
				View view = viewMap.get(position);
				final ViewHolder holder;
				if (view == null) {
					view = inflater.inflate(R.layout.nearest_list_item, parent,
							false);
					holder = new ViewHolder();
					holder.nickName = (TextView) view
							.findViewById(R.id.nearest_list_item_nickName);
					holder.signature = (TextView) view
							.findViewById(R.id.nearest_list_item_idiograph);
					holder.distance = (TextView) view
							.findViewById(R.id.nearest_list_item_distance);
					holder.headImage = (ImageView) view
							.findViewById(R.id.nearest_list_item_head_img);
					holder.age = (TextView) view
							.findViewById(R.id.nearest_list_item_age);
					holder.genderImage = (ImageView) view
							.findViewById(R.id.nearest_list_item_gender_img);
					holder.constellation = (TextView) view
							.findViewById(R.id.nearest_list_item_constellation);
					view.setTag(holder);
					viewMap.put(position, view);
				} else {
					holder = (ViewHolder) view.getTag();
				}

				NearestListItem item = items.get(position);
				holder.nickName.setText(item.getNickName());
				SpannableString spannableString = ExpressionUtil
						.getExpressionString(context, item.getSignature());
				holder.signature.setText(spannableString);
				if (item.getSex().equals("m")) {
					holder.genderImage.setBackgroundDrawable(context
							.getResources().getDrawable(
									R.drawable.friends_item_male));
				} else {
					holder.genderImage.setBackgroundDrawable(context
							.getResources().getDrawable(
									R.drawable.friends_item_female));
				}
				holder.constellation.setText(item.getConstellation());
				holder.distance.setText(item.getDistance() + "KM");
				FinalBitmap.create(context).display(holder.headImage,
						item.getHeadImage());
				return view;
			}
			return null;
		}
	}

	@Override
	public void show() {
		getListItems((new RefreshAsyncHttpResponseHandler()));
	}

}